package com.qfmy.app.service.impl.community;

import com.qfmy.app.config.ThreadPoolConfig;
import com.qfmy.app.mapper.community.PostLikeMapper;
import com.qfmy.app.mapper.community.PostMapper;
import com.qfmy.app.service.community.PostLikeService;
import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.model.entity.community.PostLike;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author 清风明月
 * @Package com.qfmy.app.service.impl.community
 * @date 2025/4/17
 * @description 帖子的点赞服务
 */
@Service
@SuppressWarnings("all")
public class PostLikeServiceImpl implements PostLikeService {

    /**
     * 注入mapper
     */
    @Autowired
    private PostLikeMapper postLikeMapper;

    /**
     * 注入帖子的mapper
     */
    @Autowired
    private PostMapper postMapper;

    /**
     * 存储帖子ID到点赞数的映射
     */
    private final ConcurrentHashMap<Integer, LongAdder> postLikes = new ConcurrentHashMap<>();

    /**
     * 存储用户点赞记录（避免重复点赞）
     */
    private final ConcurrentHashMap<String, Boolean> userLikeRecords = new ConcurrentHashMap<>();

    /**
     * 帖子的点赞服务
     * @param postId 帖子ID
     */
    @Override
    public void addPostLike(Integer postId) {
        // 获取用户ID
        Integer userId = getUserId();

        // 检查用户是否已经点赞
        if (hasUserLiked(postId, userId)) {
            throw new BaseException(ResultCodeEnum.APP_COMIC_LIKE_EXIST);
        }

        // 如果帖子的点赞计数器不存在，则初始化
        postLikes.computeIfAbsent(postId, k -> new LongAdder());

        // 原子地增加点赞数
        postLikes.get(postId).increment();

        // 记录用户点赞状态
        recordUserLike(postId, userId);
    }

    /**
     * 获取用户ID
     * @return 用户ID
     */
    private Integer getUserId() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        // 判断是否登录
        if (loginUser == null) {
            throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return loginUser.getUserId();
    }

    /**
     * 检查用户是否已经点赞
     * @param postId 帖子ID
     * @param userId 用户ID
     * @return 是否已点赞
     */
    private boolean hasUserLiked(Integer postId, Integer userId) {
        return userLikeRecords.containsKey(getUserLikeKey(postId, userId));
    }

    /**
     * 记录用户点赞状态
     * @param postId 帖子ID
     * @param userId 用户ID
     */
    private void recordUserLike(Integer postId, Integer userId) {
        userLikeRecords.put(getUserLikeKey(postId, userId), true);
        //创建点击对象
        CompletableFuture.runAsync(()->{
            PostLike postLike = new PostLike();
            postLike.setPostId(Long.valueOf(postId));
            postLike.setUserId(userId);
            postLikeMapper.insert(postLike);
        }, ThreadPoolConfig.executorService);
        //异步更新点赞数
        CompletableFuture.runAsync(() ->postMapper.updateLikeCount(postId), ThreadPoolConfig.executorService);

    }

    /**
     * 生成用户点赞的唯一键
     * @param postId 帖子ID
     * @param userId 用户ID
     * @return 唯一键
     */
    @NotNull
    @Contract(pure = true)
    private String getUserLikeKey(Integer postId, Integer userId) {
        return postId + ":" + userId;
    }

    /**
     * 获取帖子的点赞数
     * @param postId 帖子ID
     * @return 点赞数
     */
    public long getPostLikes(Integer postId) {
        return postLikes.getOrDefault(postId, new LongAdder()).sum();
    }
}